<template>
    <div>
        <div class="flex_between">
            <h2> {{ titleTName }}{{ titleName }} </h2>
            <el-button type="primary" size="mini" @click="openGoods" icon="el-icon-plus">选择{{ titleTName }}{{ titleName }}</el-button>
        </div>
        <div class="basc-info-card mt10" v-if="vList && vList.length > 0" :style="{maxHeight: stateHooks.leftHeight - 360 + 'px',overflow: 'auto'}">
            <div v-for="(item, gindex) in vList" :key="'gindex' + gindex">
                <div class="flex_row" v-for="(zitem, z_gindex) in item.spec_unit_ls" :key="'z_gindex' + z_gindex">
                    <div class="mb-box-cell flex1">
                        <div class="flex_between">
                            <div class="flex_row" style="width: 40%;overflow: hidden;">
                                <div class="obj-gdimg-box">
                                    <img :src="item.img" alt="" class="obj-avatar">
                                </div>
                                <div class="ml10" style="flex: 1;overflow: hidden;">
                                    <div class="bold font_size14" style="max-width: 100%;">{{ item.gdname || '--' }}
                                    </div>
                                    <div class="font_size12">{{ zitem.spec_title || '--' }}</div>
                                    <div class="font_size12" v-if="zitem.txt">备注：{{ zitem.txt }}</div>
                                </div>
                            </div>
                            <div style="flex: 1;justify-items: flex-end;">
                                <div class="obj-info">
                                    <div class="price-input-row flex_row">
                                        <div class="price-input-item">
                                            <span class="mr5">价格:</span>
                                            <el-input-number v-model="zitem.price" :precision="2" :step="1" :min="0"
                                                size="small" controls-position="right"
                                                @change="onPriceChange(gindex, z_gindex, 'price', $event)"
                                                class="price-input" :disabled="!LIMIT_STOREKEEEPER_EDIT_PRICE">
                                            </el-input-number>
                                            <span class="ml5">({{ '元' }})</span>
                                        </div>
                                        <div class="price-input-item">
                                            <span class="mr5">数量:</span>
                                            <el-input-number v-model="zitem.number" :min="0" size="small"
                                                controls-position="right"
                                                @change="onPriceChange(gindex, z_gindex, 'number', $event)"
                                                class="number-input">
                                            </el-input-number>
                                            <span v-if="zitem.unit_title" class="ml5">({{ zitem.unit_title || ''
                                                }})</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="del-box ml5" @click="removeGoods(gindex, z_gindex)">
                        <i class="el-icon-delete-solid"></i>
                    </div>
                </div>
            </div>
            <div class="flex_center_column mt10 mb20 font_black9"> 已加载完所有数据~  </div>
        </div>
        <el-empty v-else :description="`新建${titleTName}单，请选择${titleName}`" :image-size="80"></el-empty>
        <div class="total-summary-box" v-if="vList && vList.length > 0">
            <div class="total-item">
                <span class="total-label">{{ titleTName }}累计金额</span>
                <span class="total-amount">￥{{ totalPrice ? totalPrice.toFixed(2) : '--' }}</span>
            </div>
            <div class="total-divider"></div>
            <div class="total-item">
                <span class="total-label">{{ titleTName }}合计数量</span>
                <span class="total-quantity">{{ totalNumber || '--' }}</span>
            </div>
        </div>
        <!-- 选择产品 -->
        <chiceGoodList ref="chiceGoodListRef" @determineFun="chooseGoods" :tabType="tabType"></chiceGoodList>
    </div>
</template>

<script setup>
import { watch, computed, defineProps, defineEmits, ref, getCurrentInstance, nextTick } from '@vue/composition-api';
const { proxy } = getCurrentInstance()
import config from "@/js/conf/Config.js"
import chiceGoodList from "@/components/commV2/chiceSkuCkModel/chiceGoodList.vue"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'
import { useOrderReceiptState } from '@/pages/warehouseManage/hooks/useOrderReceiptState.js'
import accessCtrl from "@/js/limit/AccessCtrl.js"; // 检测权限

const { stateHooks } = useCommonHooks()
const { tabType, getEventInfo, query } = useOrderReceiptState()

import util from '@/js/util/Util.js'

const props = defineProps({
    typeText: {
        type: [String, Number],
        default: '商品',
    },
    list: {
        type: Array,
        default: () => ([])
    },
});

const titleName = computed(() => {
    return '商品'
})

const titleTName = computed(() => {
  return tabType.value == 'into_warehouse' ? '入库' :
    tabType.value == 'transfer_warehouse' ? '调拨' :
      tabType.value == 'out_warehouse' ? '出库' : ''
})

const emit = defineEmits(['load-more', 'item-change', 'selected', 'cartSaveCallBack']);
const totalPrice = computed(() => {
    let total = 0
    if (vList.value && vList.value.length > 0) {
        vList.value.forEach(item => {
            item?.spec_unit_ls.forEach(vm => {
                total += Number(vm.price) * Number(vm.number)
            })
        })
    }
    return total
})
const totalNumber = computed(() => {
    let number = 0
    if (vList.value && vList.value.length > 0) {
        vList.value.forEach(item => {
            item?.spec_unit_ls.forEach(vm => {
                number += Number(vm.number)
            })
        })
    }
    return number
})

// 处理价格或数量变化
const onPriceChange = async (gindex, zindex, field, value) => {
    if (value === null || value === undefined) {
        return;
    }
    const newList = JSON.parse(JSON.stringify(vList.value));
    if (newList[gindex] && newList[gindex].spec_unit_ls[zindex]) {
        newList[gindex].spec_unit_ls[zindex][field] = value;
    }
    vList.value = newList;
    // 等待下一个 tick 确保 DOM 已更新
    await nextTick();
    // 向父组件发送整个列表
    // emit('item-change', vList.value);
    // 实时保存到接口
    let spec_unit_ls = await getSpecUnitLs()
    cartSave(spec_unit_ls);
};

// 处理选择产品
const chiceGoodListRef = ref(null)
const openGoods = () => {
    if (chiceGoodListRef.value) {
        chiceGoodListRef.value.initData({
            shopid_yd: '',
        })
        chiceGoodListRef.value.dialogVisible = true
    }
};

const removeGoods = (gindex, z_gindex) => {
    proxy.$confirm('确定删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        vList.value[gindex].spec_unit_ls[z_gindex].number = 0
        let spec_unit_ls = await getSpecUnitLs()
        cartSave(spec_unit_ls);
    })
}

// 过滤上传数据
const getSpecUnitLs = async () => {
    let spec_unit_ls = []
    vList.value.forEach(item => {
        item.spec_unit_ls.forEach(vm => {
            spec_unit_ls.push({
                ...vm,
                gdid: item.gdid,
                discount_r: "100",
                isChangePriceId: false,
                price_0: vm.price,
                randstr: util.uuid(),
            })
        })
    })
    return spec_unit_ls
}

// 选择商品后的回调
const chooseGoods = async (selectedGoods) => {
    console.log("selectedGoods：", selectedGoods)
    let newList = []
    selectedGoods && selectedGoods.length > 0 ? newList = await selectedGoods.map((v) => {
        return {
            ...v,
            gdname: v.gd_title,
            spec_title: v.doc,
            unit_title: v.title,
            discount_r: "100",
            id: "",
            isChangePriceId: false,
            price_0: v.price,
            randstr: util.uuid(),
            unitid: v.unit_id
        }
    }) : []
    if (newList && newList.length > 0) {
        cartSave(newList)
    }
};

// 开单购物车-加购/修改价格数量
const cartSave = async (spec_unit_ls_m) => {
    let params = {
        allCount: 0,
        totalMoney: 0,
        type: query.value.type,
        spec_unit_ls_m,
    }
    try {
        let res = await proxy.$api({ url: config.ck_order_cart_save, data: params })
        if (res.status == 1) {
            proxy.$message({
                message: '操作成功',
                type: 'success'
            })
            emit('cartSaveCallBack', res.data);
        }
    } catch (error) {
        console.error('开单购物车-加购/修改价格数量失败:', error)
    }
}

const vList = ref([])
watch(() => props.list, (newVal) => {
    vList.value = newVal || []
}, {
    deep: true,
    immediate: true
})

const LIMIT_STOREKEEEPER_EDIT_PRICE = ref(false); //单据经手人可改
const initPermission = async () => {
  LIMIT_STOREKEEEPER_EDIT_PRICE.value =  await accessCtrl.getStorekeeperEditPriceLimit(); //单据经手人可改
}
initPermission()

</script>

<style lang="scss" scoped>
div {
    line-height: 1.5 !important;
}

.basc-info-card {
    box-sizing: border-box;
    overflow: hidden;
    padding: 0 12px;
    border-radius: 8px 8px 0 0;
    border: 1px solid #e2e8f0;
}

.mb-box-cell {
    box-sizing: border-box;
    overflow: hidden;
    padding: 6px 0;
    border-bottom: 1px solid #e2e8f0;
}

.obj-ls-box {
    margin-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
    padding-bottom: 10px;
}

.obj-ls-box:last-child {
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
    border-bottom: none !important;
}

.obj-gdimg-box {
    height: 50px;
    width: 50px;
    border-radius: 2px;
    border: 1px solid #f5f9f9;
    overflow: hidden;
    background-color: #f5f9f9;
}

.obj-avatar {
    height: 100%;
    width: 100%;
    border-radius: 6px;
}

.price-input-row {
    display: flex;
    flex-direction: row;
    gap: 20px;
}

.price-input-item {
    display: flex;
    align-items: center;
    font-size: 12px;
    width: 200px;
}

.price-input,
.number-input {
    width: 120px;
}

::v-deep .el-input-number {
    .el-input__inner {
        padding-left: 8px;
        padding-right: 30px;
    }
}

::v-deep .el-input-number--mini {
    .el-input__inner {
        height: 24px;
        line-height: 24px;
    }

    .el-input-number__increase,
    .el-input-number__decrease {
        height: 12px;
        line-height: 12px;
    }
}

.del-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: #e9f1f1;
    cursor: pointer;
    font-size: 14px;
    color: #f56c6c;
    margin-left: 10px;
}

::v-deep .el-empty {
    padding: 20px 0 0 !important;
}

.total-summary-box {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 6px 14px;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-radius: 0 0 12px 12px;
    border: 1px solid #e2e8f0;
    border-top: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.total-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.total-label {
    font-size: 14px;
    color: #64748b;
    font-weight: 500;
}

.total-amount {
    font-size: 18px;
    font-weight: 700;
    color: #e11d48;
    text-shadow: 0 1px 2px rgba(225, 29, 72, 0.1);
}

.total-quantity {
    font-size: 16px;
    font-weight: 600;
    color: #0f172a;
}

.total-divider {
    width: 1px;
    height: 24px;
    background-color: #cbd5e1;
    margin: 0 24px;
}
</style>